extends Area2D
class_name MushroomDrag

# 内部参数
var can_drag: bool = true
var is_drag: bool = false
var drag_offset = Vector2.ZERO
var original_z_index = 0


# 获取的节点
@onready var mushroom: Node2D = $"../.."
@onready var body: CharacterBody2D = $".."
# 信号

# 开始时连接输入信号
func _ready():
	connect("input_event",_on_input)
# 获取输入通知
func _on_input(viewport, event, shape_idx):
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		if event.pressed and mushroom.can_drag:
			start_drag()
			print("开始拖拽")
		else:
			end_drag()
			print("停止拖拽")

# 开始拖拽方法
func start_drag():
	if not is_drag:
		is_drag = true
		drag_offset = body.global_position - get_global_mouse_position()
		original_z_index = z_index
		z_index = 100
		mushroom.set_mushroom_stat_oncontrol()
		
func _process(delta: float) -> void:
	if is_drag:
		if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
			var new_position = get_global_mouse_position() + drag_offset
			body.global_position = new_position
		else:
			end_drag()

# 停止拖找方法
func end_drag():
	if is_drag:
		is_drag = false
		mushroom.z_index = original_z_index
		mushroom.set_mushroom_stat_waiting()
	return
		
